<template>
  <div class="container" id="container">
    <div class="mescroll" ref="mescroll" :style="{bottom:isiPx?'0.7rem':'0rem'}">
      <div class="mescroll-wrapper">
        <!-- 页面头部 -->
        <div class="header relative">
          <img :src="basePageInfo.banner[0].img" alt="">
          <span id="share" @click="shareForWechat">
            <!-- 分享 -->
            <img :src="pageImgArr.pic04" alt="">
          </span>
        </div>
        <!-- 专区模块 -->
        <div class="zq-region relative">
          <div v-for="(item,index) in basePageInfo.tags" :key="index" @click="goPageDetail(item)">
            <img :src="item.img" alt="">
          </div>
        </div>
        <!-- 链接入口 -->
        <div class="page-link relative" :class="{'fixed':fixedScroll}">
          <img :src="pageImgArr.pic03" alt="">
          <div :class="['width_25_'+(index+1)]" v-for="(item,index) in pageLink" :key="index" @click="jumpForPage(item.links)"></div>
        </div>
        <div class="abandon" ref="abandon" :class="{'fixed':fixedScroll}"></div>
        <!-- 领券 -->
        <div class="coupon" v-if="showCouponEntry" @click="handleBanner(basePageInfo.ad[0],0)">
          <img :src="basePageInfo.ad[0].img" alt="">
        </div>
        <!-- 商品 -->
        <div class="goods-wrapper">
          <GoodsItem :parentData="item" :parentStyle="selfStyle" @childEvent="goForGoodsDetail" v-for="(item,index) in dataList" :key="index"/>
        </div>
      </div>
    </div>
    <!-- 1020会场入口 -->
    <div class="category" :class="{'isIphoneX':isiPx}" v-if="isBottom">
      <img src="https://astatic.shandjj.com/static/Active2019/Oct/Member/img/scene.png" alt="">
      <div :class="'item0'+(index+1)" v-for="(item,index) in 4" :key="index" @click="jumpOtherPage(index)"></div>
    </div>
  </div>
</template>

<script>
  import MeScroll from 'mescroll.js'
  import 'mescroll.js/mescroll.min.css'
  import GoodsItem from '../shopItem.vue'
  import MaskModal from 'components/maskDown/index.js'
  import { getLimitBaseApi, getGoodsListApi } from "@/apis/privateApi.js";
  import { getGlobalCouponList,getUserCouponStatusList } from "@/apis/publicApi.js";
  import { getParamsFromUrl } from '../../../utils/self.js'
  import wx from 'weixin-js-sdk';
  export default {
    name: 'secondShop',
    components:{ GoodsItem },
    data(){
      return{
        userId:-1,
        isBottom:false,//是否有820会场
        selfStyle:{width:'50%'},
        isGetCouponed:false,
        couponId:'',//优惠券id
        showCouponEntry:false,
        isiPx: /iphone/gi.test(navigator.userAgent) && (screen.height == 812 && screen.width == 375),
        positionTimer:null,
        pageLink:[
          {id:1,links:'https://a.shandjj.com/longTerm/TimeOnsaleV2/index.html'},
          {id:2,links:'https://a.shandjj.com/longTerm/LimitOnsaleV2/index.html'},
        ],
        mescroll:null,//滚动器
        fixedScroll:false,//是否吸顶
        navTabPos:0,//nav的位置
        pageImgArr:{},//页面图片
        dataList:[],//页面数据数组
        hasNext:true,//是否有下一页
        mainTagId:'',//主分类商品id
        basePageInfo:{ banner:[{img:''}], tags:[], ad:[{}] }
      }
    },
    async created(){
      let that = this;
      if( this.shareJudge('isshare') ){ 
        let url = window.location.href.split("?")[0];
        window.location.href = `sdjj://web.sdjj.com/active?url=${url}`;
        MaskModal(); 
      }
      if( this.shareJudge('isBottom') ){ this.isBottom=true }
      this.initPageImg();
      await this.getPageBaseInfo();
      this.$navtiveUtils.checkLogin();
      window.isLogin = function(u) {
        if (u) {
          let userInfo = { user_id: u };
          window.userInfo = userInfo;
          that.userId = u;
          that.getCouponStatus(u);
        } else {
          that.$navtiveUtils.onLogin();
        }
      };
      // 小程序处理
      wx.miniProgram.getEnv(function (res) {
        if (res.miniprogram) {
          let baseInfo = getParamsFromUrl();
          if(baseInfo.userid>0){
            that.userId=baseInfo.userid;
            that.getCouponStatus(that.userId);
          }else{
            let url = decodeURIComponent(`${that.shareJudge('inviterId')}&linkId=${self.location.href}`);
            wx.miniProgram.navigateTo({ url: `/pages/account/authorize/authorize?inviterId=${url}` })
          }
        }
      });
    },
    mounted(){
      let that=this;
      this.positionTimer = setTimeout(function(){
        that.navTabPos=that.$refs.abandon.offsetTop;
      },300);
      this.mescroll = new MeScroll(that.$refs.mescroll,{
        up: { 
          auto: true,  
          callback: this.upCallback,  
          page: { num: 0, size: 20  }, 
          noMoreSize: 3 ,
          htmlNodata:`<div class="deadline upwarp-nodata"><span>亲，我们是有底线哦~</span></div>`,
          toTop: {	src: that.pageImgArr.toTop, 	offset: 1000 },
          empty: { warpId:'container', icon:'http://www.mescroll.com/demo/res/img/mescroll-empty.png',tip:'暂无相关数据!' },
          onScroll:function(mescroll,y,isUp){
            that.fixedScroll =  y>that.navTabPos ? true :false ;
          }
        }
      });
    },
    methods:{
      //引入页面图片
      initPageImg(){
        this.pageImgArr={
          pic03:require('../../../assets/img/secondShopV2/secondShop03.jpg'),
          pic04:require('../../../assets/img/publicImg/share_white.png'),
          pic05:require('../../../assets/img/secondShop/secondShop05.jpg'),
          pic06:require('../../../assets/img/secondShop/secondShop06.gif'),
          toTop:require('../../../assets/img/publicImg/totop.png'),
          category:require('../../../assets/img/secondShopV2/bottom_btn.png'),
        }
      },
      //获取页面配置信息
      async getPageBaseInfo(){
        await getLimitBaseApi().then(res =>{
          if(res.code==200){
            this.basePageInfo.banner = res.base.banner;
            this.basePageInfo.tags =res.base.tags;
            this.basePageInfo.ad = res.base.ad;
            this.couponId = res.base.ad[0].couponId;
            this.showCouponEntry = res.base.ad.length>0 ? true:false;
            this.mainTagId = res.base.mainTagId;
            this.mescroll.resetUpScroll();
          }
        })
      },
      //顶部banner操作
      handleBanner(obj,type){
        let idValue= type ? obj.target.value : obj.couponId;
        if(obj.type==1){
          this.getCouponAction(idValue);
        }else if(obj.type ==2){
          if(obj.target.type==0){
            this.goForSpecialDetail(obj.target.value);
          }else if(obj.target.type==1){
            this.goForGoodsDetail(obj.target.value);
          }else if(obj.target.type==2){
            this.jumpForPage(obj.target.value);
          }
        }
      },
      //领取状态接口
      async getCouponStatus(userId){
        await getUserCouponStatusList(userId,this.couponId).then(({data}) =>{
          this.isGetCouponed = data.status > 0 ? true : false ;
        })
      },
      //领取动作接口
      getCouponAction(couponId){
        let that=this;
        if(this.userId && this.userId>0){
          let userId = this.userId;
          if(that.isGetCouponed){ 
            that.$vux.toast.text(`${'您已领取过该券!'}`, "middle"); 
            return false;
          }
          getGlobalCouponList(userId,couponId).then(res =>{
            if (res.code == 200 && res.status == "success") {
              that.isGetCouponed=true;//领取券成功
              that.$vux.toast.text(`${'优惠券领取成功！'}`, "middle");
            }
          })
        }else{
          that.$navtiveUtils.checkLogin();
        }
      },
      goForGoodsDetail(id){
        this.$navtiveUtils.jump2goods(id);
      },
      goForSpecialDetail(id){
        this.$navtiveUtils.jump2special(id);
      },
      upCallback (page) {
        let that = this ;
        this.getListDataFromNet(page.num, page.size, (successData) =>{
          if (page.num == 1) { that.dataList=[] };//刷新时清空数据
          that.dataList = that.dataList.concat(successData);
          that.$nextTick(() => {
            //传入当前页面数据与是否有下一页
            that.mescroll.endSuccess(page.size,that.hasNext);
          });
        }, (error) =>{
          this.mescroll.endErr();
        });
      },
      getListDataFromNet (pageNum, pageSize,successCallback, errorCallback) {
        if(!this.mainTagId){ return false}//防止mainTagId未返回值调用接口
        let params={ tagId:this.mainTagId, page:pageNum, pageSize:pageSize };
        getGoodsListApi(params).then(res =>{
          let resData = res.goodsList.goods;//接口返回的数据
          this.hasNext = res.goodsList.hasNext ? true : false ;//判断是否还有下一页
          successCallback && successCallback(resData);//调用成功回调
        }).catch(error =>{
          errorCallback && errorCallback();//调用失败回调
        })
      },
      jumpForPage(links){ 
        window.location.href=links; 
      },
      jumpOtherPage(index){
        if(index==0){
          window.location.href='https://a.shandjj.com/Active2019/Nov/Member/index.html';
        }else if(index==1){
          window.location.href='https://a.shandjj.com/longTerm/TimeOnsaleV2/index.html?isBottom=1';
        }else if(index==3){
          window.location.href='https://a.shandjj.com/longTerm/LimitOnsaleV2/index.html?isBottom=1';
        }
      },
      goPageDetail(page){
        let trandition=window.location.hostname;
        let baseUrl=window.location.origin;
        if(trandition=='localhost'){
          baseUrl=baseUrl+'/views/SecondShopV2/pageDetail.html';
        }else{
          baseUrl=baseUrl+'/default/Active2019/SecondShopV2/views/SecondShopV2/pageDetail.html';
        }
        window.location.href=baseUrl+'?pageName='+page.id+'&title='+page.title;
      },
      shareJudge(e) {
        let temp = window.location.search.replace('?', '').split('&')
        let isFlag = false,value = '';
        for (let index = 0; index < temp.length; index++) {
          if (temp[index].split('=').indexOf(e)>-1) { value = temp[index].split('=')[1] }
          isFlag += temp[index].split('=').indexOf(e)>-1;
        }
        return isFlag ? value : false
      },
      shareForWechat() {
        let that = this;
        let pageTitle=document.title ;
        setTimeout(function() {
          that.$navtiveUtils.share(pageTitle, "潮流精选好货，限时折扣中，快来抢购！","");
        }, 300);
      }
    },
    destroyed(){
      window.clearTimeout(this.positionTimer);
      this.positionTimer = null;
      this.mescroll.destroy();
    }
  }
</script>
<style lang="less">
.mescroll-upwarp.mescroll-hardware{ padding: 0; }
.deadline{
  font-size: 0.28rem;
  text-align: center;
  .line{
    display: block;
    width: 2.6rem;height: 0.08rem;
    margin: 0.25rem auto 0;
    border-radius: 0.08rem;
    background: #000;
  }
}
html .mescroll-totop{bottom: 2.5rem}
</style>

<style lang="less" scoped>
.container{
  width: 100%;
  height: 100%;
}
.mescroll {
  width: 100%;
  position: absolute;
  top: 0;
  bottom: 0;
  height: auto;
  &::-webkit-scrollbar{
    width: 0;
    height: 0;
  }
}
.relative{position: relative;}
.header{
  height: 2.42rem;
  position: relative;
  #share{
    width: 0.8rem;
    height: 0.45rem;
    line-height: 0.45rem;
    text-align: center;
    font-size: 0.3rem;
    color: #ffffff;
    position: absolute;
    top: 0.2rem;right: 0;
    border-radius: 0.45rem 0 0 0.45rem;
    img{
      display: inline-block;
      width: 0.45rem;
      height: 0.45rem;
      vertical-align: top;
    }
  }
  .container-swiper{
    height: 2.45rem;
  }
}
.zq-region{
  height: 1.87rem;
  &>div{
    float: left;
    width: 25%;
    height: 100%;
  }
}
.page-link{
  height: 1.2rem;
  &.fixed{
    width: 100%;
    position: fixed;
    top: 0;left: 0;
    z-index: 10;
  }
  &>div{
    width: 50%;
    height: 100%;
    position: absolute;
    top: 0;left: 0;
  }
  div.width_25_2{left: 50%}
}
.abandon.fixed{
  padding-top: 1.2rem;
}
.goods-wrapper{
  display: flex;
  flex-wrap: wrap;
}
.category{
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 100;
  &.isIphoneX{border-bottom: 0.7rem solid #fff;}
  &>div{
    width: 1.5rem;
    height: 100%;
    position: absolute;
    top: 0;left: 0.28rem;
    &.item02{left: 2.08rem}
    &.item03{left: 3.92rem}
    &.item04{left: 5.68rem}
  }
}
</style>